<template>
  <!-- 添加/编辑  字段弹窗 -->
  <h-drawer
    :width="800"
    unit="px"
    :model-value="isOpen"
    :title="title"
    :loading="loading"
    @close="onClose"
  >
    <el-form
      ref="formRef"
      label-position="top"
      inline-message
      class="modal_form_content"
      :rules="rules"
      :model="networkFieldVo"
    >
      <el-form-item label="字段名称" class="form-item" prop="name">
        <el-input
          v-model.trim="networkFieldVo.name"
          maxlength="10"
          clearable
          placeholder="请输入名称"
        />
      </el-form-item>
      <el-form-item label="字段类型" class="form-item" prop="type">
        <el-select v-model="networkFieldVo.type" :disabled="networkFieldVo.id !== ''">
          <el-option
            v-for="item in props.type == 0 ? fieldOption0 : fieldOption1"
            :key="item.value"
            :value="item.value"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提示信息" class="form-item">
        <el-input
          v-model.trim="networkFieldVo.tip"
          maxlength="20"
          clearable
          placeholder="请输入提示信息"
        />
      </el-form-item>
      <div class="radio_group">
        <el-form-item label="字段状态" class="same_line" prop="status">
          <el-radio-group v-model="networkFieldVo.status">
            <el-radio :value="false" size="small">启用</el-radio>
            <el-radio :value="true" size="small">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否必填" class="same_line" prop="required">
          <el-radio-group v-model="networkFieldVo.required">
            <el-radio :value="true" size="small">必填</el-radio>
            <el-radio :value="false" size="small">可填</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="移动端显示" class="same_line" prop="mobileShow">
          <el-radio-group v-model="networkFieldVo.mobileShow">
            <el-radio :value="true" size="small">显示</el-radio>
            <el-radio :value="false" size="small">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <!-- 单选/多选的字段内容 -->
      <template v-if="networkFieldVo.type == 3 || networkFieldVo.type == 4">
        <template v-for="(item, index) in networkFieldVo.contents" :key="index">
          <el-form-item
            :prop="`contents[${index}][val]`"
            :rules="rules.val"
            :label="`字段内容${index + 1}`"
          >
            <div class="field_content">
              <el-input
                v-model.trim="item.val"
                class="text-input"
                style="width: 455px"
                clearable
                placeholder="请输入字段内容"
                maxlength="20"
              />
              <div class="btn_group">
                <h-link
                  v-if="networkFieldVo.contents.length > 1"
                  type="error"
                  @click="handleDele(index, item)"
                  >删除</h-link
                >
                <h-link v-if="index === 0" @click="addFieldContent">新增</h-link>
              </div>
            </div>
          </el-form-item>
        </template>
      </template>
      <span v-if="networkFieldVo.type == 5 || networkFieldVo.type == 6 || networkFieldVo.type == 7">
        <el-form-item label="最大尺寸(MB)" prop="uploadSize" style="margin-bottom: 18px">
          <el-input
            v-model.trim="networkFieldVo.uploadSize"
            type="number"
            clearable
            placeholder="请输入尺寸"
            @input="limitNum(networkFieldVo.uploadSize, 100)"
            @change="networkFieldVo.uploadSize ? '' : (networkFieldVo.uploadSize = 1)"
          />
        </el-form-item>
        <el-form-item label="上传数量" class="form-item" prop="uploadQty">
          <el-input
            v-model.trim="networkFieldVo.uploadQty"
            type="number"
            clearable
            placeholder="请输入数量"
            @input="limitNum(networkFieldVo.uploadQty, 10)"
            @change="networkFieldVo.uploadQty ? '' : (networkFieldVo.uploadQty = 1)"
          />
        </el-form-item>
      </span>
    </el-form>

    <template #footer>
      <HPlainBgButton
        v-show="networkFieldVo.id && !props.isHideDelBtn"
        is-modal
        type="error"
        @focus="(e: Event) => (e.target as HTMLButtonElement).blur()"
        @click="onDelNetworkField(networkFieldVo)"
        >删除</HPlainBgButton
      >
      <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </h-drawer>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw, watch, toRefs } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Delete } from '@element-plus/icons-vue'
  import _ from 'lodash'

  const props = defineProps({
    title: String, //新增/修改字段弹窗
    isOpen: Boolean,
    loading: Boolean, // 保存字段加载动画
    fieldVo: Object,
    type: {
      type: Number,
      default: 0,
    },
    isHideDelBtn: {
      type: Boolean,
      default: () => false,
    },
  })
  const { title, isOpen, loading, fieldVo, type } = toRefs(props)
  const emits = defineEmits(['on-save', 'on-close', 'on-delete'])
  // 字段对象
  const networkFieldVo = ref()
  watch(isOpen, (n) => {
    if (n) {
      networkFieldVo.value = _.cloneDeep(fieldVo.value)
    }
  })
  // 表单元素
  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
    val: [{ required: true, message: '请输入字段内容', trigger: ['blur', 'change'] }],
    required: [{ required: true, trigger: 'blur' }],
    mobileShow: [{ required: true, message: '请选择是否前端显示', trigger: 'blur' }],
    status: [{ required: true, message: '请选择字段状态', trigger: 'blur' }],
    type: [{ required: true, message: '请选择字段类型', trigger: 'blur' }],
    uploadSize: [
      { required: false, message: '请输入最大尺寸', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    uploadQty: [
      { required: false, message: '请输入上传数量', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })
  const limitNum = (val, n) => {
    if (val > n) {
      val = n
    } else if (val == 0 && val != '') {
      val = 1
    }
    if (n == 100) {
      networkFieldVo.value.uploadSize = val
    } else {
      networkFieldVo.value.uploadQty = val
    }
  }
  const onClose = () => {
    emits('on-close')
  }
  // 1-文本，2-多行文本，3-单选，4-多选，5-多图，6-附件，7-视频，8-评分
  const fieldOption0 = [
    { value: 1, name: '文本' },
    { value: 2, name: '多行文本' },
    { value: 3, name: '单选' },
    { value: 4, name: '多选' },
    { value: 5, name: '多图' },
    { value: 6, name: '附件' },
    { value: 7, name: '视频' },
    { value: 8, name: '评分' },
    { value: 9, name: '日期' },
    { value: 10, name: '日期时间' },
  ]

  // 1-文本，2-多行文本，3-单选，4-多选，5-多图，6-附件，7-视频
  const fieldOption1 = [
    { value: 1, name: '文本' },
    { value: 2, name: '多行文本' },
    { value: 3, name: '单选' },
    { value: 4, name: '多选' },
    { value: 5, name: '多图' },
    { value: 6, name: '附件' },
    { value: 7, name: '视频' },
    { value: 9, name: '日期' },
    { value: 10, name: '日期时间' },
  ]
  // 新增字段内容
  const addFieldContent = () => {
    networkFieldVo.value.contents.push({ id: '', val: '' })
  }

  // 删除字段内容
  const handleDele = (index, obj) => {
    networkFieldVo.value.contents.splice(index, 1)
    if (obj.id) {
      if (!networkFieldVo.value.delContentIds) {
        networkFieldVo.value.delContentIds = []
      }
      networkFieldVo.value.delContentIds.push(obj.id)
    }
  }

  // 修改弹窗的删除按钮
  const onDelNetworkField = (obj) => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      icon: markRaw(Delete),
      message: `是否删除字段名称[ ${obj.name} ]? 删除后将不可恢复`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '删除中...'
          emits('on-delete', [obj.id])
          setTimeout(() => {
            done()
            instance.confirmButtonLoading = false
          }, 1000)
        } else {
          done()
        }
      },
    }).catch(() => {})
  }

  // 保存字段
  const saveData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        if (networkFieldVo.value.type === 3 || networkFieldVo.value.type === 4) {
          if (networkFieldVo.value.contents.length == 0) {
            ElMessage({
              message: '字段内容不能为空',
              type: 'warning',
              duration: 5000,
              showClose: true,
              plain: true,
            })
            return
          }
          if (networkFieldVo.value.contents.filter((f) => f.val == '').length > 0) {
            ElMessage({
              message:
                networkFieldVo.value.type === 3 ? '单选字段内容不能为空' : '多选字段内容不能为空',
              type: 'warning',
              duration: 5000,
              showClose: true,
              plain: true,
            })
            return
          }
          const tem = []
          for (let index in networkFieldVo.value.contents) {
            const con = networkFieldVo.value.contents[index]
            if (tem.indexOf(con.val) !== -1) {
              ElMessage({
                message: `第 ${Number(index) + 1} 行的字段内容[ ${con.val} ]已重复`,
                type: 'warning',
                duration: 5000,
                showClose: true,
                plain: true,
              })
              return
            }
            tem.push(con.val)
          }
        }
        if (
          networkFieldVo.value.type === 5 ||
          networkFieldVo.value.type === 6 ||
          networkFieldVo.value.type === 7
        ) {
          if (networkFieldVo.value.uploadSize > 100) {
            ElMessage({
              message: `最大尺寸上限值 <= 100`,
              type: 'warning',
              duration: 5000,
              showClose: true,
              plain: true,
            })
            return
          }
          if (networkFieldVo.value.uploadQty > 10) {
            ElMessage({
              message: `上传数量上限值 <= 10`,
              type: 'warning',
              duration: 5000,
              showClose: true,
              plain: true,
            })
            return
          }
        }
        if (!(networkFieldVo.value.type === 3 || networkFieldVo.value.type === 4)) {
          networkFieldVo.value.contents = []
        }
        emits('on-save', networkFieldVo.value)
      }
    })
  }

  // 返回方法
  defineExpose({})
</script>

<style scoped lang="scss">
  .radio_group {
    display: flex;
    flex-wrap: wrap;
    row-gap: 12px;
    column-gap: 72px;
  }

  // 单选、多选字段内容的表单项
  .field_content {
    display: flex;
    column-gap: 5px;
    align-items: center;
    width: 100%;

    .btn_group {
      display: flex;
      column-gap: 5px;
      height: 28px;
      align-items: center;
    }
  }

  // 字段内容标题的表单项
  .field_content_form_item {
    :deep(.el-form-item__label) {
      margin: 0 !important;
    }
  }

  .add-dialog2 {
    .form-text {
      .form-item {
        margin-bottom: 18px;

        .el-radio {
          margin-right: 18px;
        }
      }

      p {
        font-size: 12px;
        color: #999;
      }
      .list {
        margin: 15px 0;
        max-height: 220px;
        overflow-y: auto;
        height: 100%;

        :deep(.el-form-item__label) {
          padding: 0;
        }

        .text-item {
          margin-bottom: 15px;

          .text-input {
            width: 280px;
          }

          .delete {
            margin-left: 12px;
            font-size: 12px;
            color: #f56c6c;
            cursor: pointer;
          }

          .el-form-item__error {
            left: 38px;
          }
        }
      }
    }
  }

  .field_type {
    :deep(.el-select__wrapper) {
      width: 100px;
    }
  }
</style>
